# -*- coding: utf-8 -*-

import requests
import json
import os



headers = {"User-Agent":
               "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36"}


# resp = requests.get(url=start_url, headers=headers)
#
# data1 = resp.content.decode()
# json_data = json.loads(data1)  # j将字符串转化为python数据类型
#
# data2 = resp.json()  # 从响应内容中获取json数据，并转化为python数据类型

# print(data1)
# print(type(data1))
#
# print('**'*20)
#
# print(data2)
# print(type(data2))

# items = data2["totalNum"]  # 从字典中通过键取值，键不存在则抛出异常
#
# print(items)

# print(data2.get("totalNum"))  # 通过get方法从字典中取值，键不存在返回None， 取值优先使用get()方法


# items = data2.get("items")

# print(items)
# print(type(items))
# print(len(items))

# item_1 = items[0]
# print(item_1)
# print(type(item_1))


def get_json_data(json_url):
    try:
        data = requests.get(url=json_url, headers=headers).json()
        return data.get("items")
    except Exception:
        print("not json data")


def download(item: dict):
    name = item.get("name")
    picUrl = item.get("picUrl")


    print(picUrl)
    with open("./photo/" + name, 'wb') as f:
        content = requests.get(url=picUrl, headers=headers).content
        f.write(content)


# for i in items:
#     download(i)


if __name__ == '__main__':

    i = 0
    index = 48 * (i+1)
    start_url = f"https://image.sogou.com/api/pic/searchList?tagQSign=&forbidqc=&entityid=&preQuery=&rawQuery=&queryList=&ie=gbk&query=%E7%84%B0%E7%81%B5%E5%A7%AC&mode=1&st=&start={index}&xml_len=48&cwidth=1920&cheight=1080&_=1600525286217"
    json_list = []

    while True:
        if i < 10:
            json_list.append(get_json_data(start_url))
            i+=1

        else:
            break

    for j in json_list:
        for k in j:
            download(k)


